﻿@using System.Web.Script.Serialization
@{
    ViewBag.Title = "List";
    Layout = "~/views/Shared/_MyLayout.cshtml";
}

@Styles.Render("~/content/fineuploader/fineuploader-3.5.0.css")
@Scripts.Render("~/content/fineuploader/fineuploader-3.5.0.js")
@Scripts.Render("~/content/fineuploader/iframe.xss.response-3.5.0.js")
@Styles.Render("~/content/statuses.css")

<style>
    .qq-upload-button {
        background-color: #428bca;
        padding: 8px 12px;
    }

    .qq-upload-list {
        text-align: left;
        display: none;
    }

    /* For the bootstrapped demos */
    li.alert-success {
        background-color: #DFF0D8;
    }

    li.alert-error {
        background-color: #F2DEDE;
    }

    .alert-error .qq-upload-failed-text {
        display: inline;
    }

    .picUploadbutton {
        display: inline-block;
    }
</style>



       
       

            <ul class="nav nav-tabs" id="myTab">
                <li class="active"><a href="#statusTab" data-toggle="tab">@T("status_tab_title")</a></li>

            </ul>


            <div class="tab-content">
                <div class="post tab-pane active" data-bind="visible:IsOwner" style="display: none" id="statusTab">
                    <!-- ko with: CustomerStatusModel-->
                    <div>
                        <div class="post_inner">
                            <textarea data-bind="value:Text" rows="5" class="form-control" placeholder=""></textarea>


                            @Html.Partial("_tagEditor")



                            <div>
                                <!-- ko foreach: Pics-->
                                <img data-bind="attr:{src: PicUrl}" />
                                <!-- /ko -->
                            </div>
                            <!-- ko if: $root.IsOwner -->
                            <input type="button" value="Post" data-bind="click:PostCustomerStatus,css:{disabled:Text()==''}" class="btn btn-primary" />
                            <div class="picUploadbutton">
                                <div id="manualUploadModeExample1" class="unstyled "></div>
                            </div>




                            <!-- /ko -->
                        </div>


                    </div>

                    <!-- /ko -->
                </div>
              
            </div>



            <!-- ko ifnot: IsOwner -->
            <!-- ko ifnot: IsFriend -->
            <input type="button" value="follow" data-bind="click:CreateFriendShip" class="btn btn-primary" />
            <!-- /ko -->
            <!-- /ko -->


            <div>
    
                  <a data-bind="click:listStatus" >all status</a>
                  <a data-bind="click:listProductStatus">all product </a>
            </div>

<div class="statuses_list" data-bind="visible:Messages().length>0" style="display: none">
                
                <ul class="media-list">
                    <!-- ko foreach: Messages-->
                    <li class="media">
                        <a data-bind="attr:{href:'/posts/'+CustomerId()}" class="pull-left">
                            <img data-bind="attr:{src: CustomerLogoUrl}" class="media-object" />
                        </a>
                       
                        <div class="media-body ">
                            <h4 class="media-heading"></h4>

                            <div class="comment-content" style="float: left" data-bind="attr:{link:'/status/' +Id()},click:GoOnePageProduct">
                                <span data-bind="html:Text"></span>
                                <!-- ko if: IsProduct-->
                                <div>
                                    <span data-bind="text:ProductStock"></span>
                                    <span data-bind="text:ProductPrice"></span>
                                </div>
                                <!-- /ko -->

                                <!-- ko foreach: Pics-->
                                <div class="comment-pictures">
                                    <img data-bind="attr:{src: PicUrl},click:ShowOriginalPic" />
                                </div>
                                <!-- /ko -->

                                <ul class="status-tagedit-list " style="border: 0px">
                                    <!-- ko foreach: Tags-->
                                    <li class="tagitem" 
                                        data-bind="text:TagName"></li>
                                    <!-- /ko -->
                                  
                                   
                                </ul>
                                
                                <div>
                                    @*<span data-bind="text:CreatedAt"></span>*@
                                </div>

                            </div>
                            <div class="operation">
                            </div>
                        </div>
                    </li>

                    <!-- /ko -->
                </ul>

                <div class="row-fluid">
                    <input type="button" value="More" data-bind="click:MoreStatus,visible:Messages().length>0" class="btn btn-default btn-block" />
                </div>
            </div>

       
        




@{
    var model = ViewBag.Model;
    var jsonStr = new HtmlString(new JavaScriptSerializer().Serialize(model));
}

@section scripts
{
    <script type="text/javascript" src="~/Scripts/jquery.signalR-1.1.2.js"></script>
    <script type="text/javascript" src="~/signalr/hubs"></script>
    <script src="~/Scripts/posts/posts.js"></script>
    <script src="~/Scripts/posts/tags.js"></script>

    <script>

        var init = @jsonStr;

        var hub = $.connection.posts;
        

        function PageInfo(customerId, pageIndex, pageSize, lastPostDate) {
            var self = this;
            self.CustomerId = ko.observable(customerId);
            self.PageIndex = ko.observable(pageIndex);
            self.PageSize = ko.observable(pageSize);
            self.LastPostDate= ko.observable(lastPostDate);

            self.NextPage = function(lpd) {
                return new PageInfo(customerId, pageIndex + 1, pageSize, lpd);
            };
            self.FirstPage = function(lpd) {
                self.PageIndex(0);
                return new PageInfo(customerId, self.PageIndex(), pageSize,lpd);
            };
        }


        function ProductStatusModel() {
            var self = this;
            self.ProductDescription = ko.observable('');
            self.ProductStock = ko.observable('');
            self.ProductPrice = ko.observable('');
            self.Pics = ko.observableArray();

            
            self.PostProductStatus = function(pv) {
                if (self.ProductDescription() != '') {

                    var message = {
                        Text: self.ProductDescription(),
                        Pics: ko.toJS(self.Pics),
                        ProductStock: self.ProductStock(),
                        ProductPrice: self.ProductPrice(),
                    };

                    hub.server.sendProductStatus(message).fail(function(err) {
                    });
                }
            };

        }

        function CustomerStatusModel() {
            var self = this;
            self.Text = ko.observable('');
            self.Pics = ko.observableArray();

            self.PostCustomerStatus = function(pv) {
                if (self.Text() != '') {

                    var message = {
                        Text: self.Text(),
                        Pics: ko.toJS(self.Pics),
                        Tags: GetTags(),
                    };

                    hub.server.send(message).fail(function(err) {
                    });
                }
            };
        }


        function GetTags() {
            var tagArr = new Array();
            $("input[name^='tag']").each(function() {
                if ($(this).val() != "") {
                    tagArr.push($(this).val());
                }
            });
            return tagArr;
        }


        function HomeTimeLineModel() {

            var self = this;


            self.ProductStatusModel = new ProductStatusModel();

            self.CustomerStatusModel = new CustomerStatusModel();

            //self.ClientId = ko.observable();
            self.CustomerId = ko.observable(init.CustomerId);
            self.IsOwner = ko.observable(init.IsOwner);
            self.IsFriend = ko.observable(init.IsFriend);


            var tempMessages = $.isEmptyObject(init.PostList) ? [] : $.map(init.PostList, function(a) {
               

                
                return BuildListItemModel(a);
            });

            self.Messages = ko.observableArray(tempMessages);
            self.PageInfo = new PageInfo(init.CustomerId, 0, 5, null);
            var listModeEnum = {
                ListStatus :0,
                ListProductStatus :1
            };

            self.ListMode = ko.observable(listModeEnum.ListStatus);
            
            self.listProductStatus = function() {

                self.ListMode(listModeEnum.ListProductStatus);

                self.PageInfo = self.PageInfo.FirstPage(null);
                $.ajax({
                    url: "/api/PostApi/HomeLineProduct",
                    type: 'post',
                    async: false,
                    data: ko.toJSON(self.PageInfo),
                    contentType: 'application/json',
                    success: function(result) {

                        if (result.Status == "0") {
                            var postList = result.PostList;

                            vm.Messages([]);

                            $.each(postList, function(index, a) {
                                
                                var item = BuildListItemModel(a);
                                vm.Messages.push(item);


                            });

                        } else {
                            //alert("保存失败：" + result.Msg);
                        }
                    }
                });
            };
            self.listStatus = function() {
                self.ListMode(listModeEnum.ListStatus);

                self.PageInfo = self.PageInfo.FirstPage(null);
                $.ajax({
                    url: "/api/PostApi/HomeLine",
                    type: 'post',
                    async: false,
                    data: ko.toJSON(self.PageInfo),
                    contentType: 'application/json',
                    success: function(result) {

                        if (result.Status == "0") {
                            var statusList = result.PostList;

                            vm.Messages([]);

                            $.each(statusList, function(index, a) {

                                var item = BuildListItemModel(a);
                                

                                vm.Messages.push(item);


                            });

                        } else {
                            //alert("保存失败：" + result.Msg);
                        }
                    }
                });
            };
            self.LastCreatedAt = function() {
                var vmMessageLength= vm.Messages().length;
                var lastMessageDateTime = vmMessageLength == 0 ? null : vm.Messages()[vmMessageLength - 1].CreatedAtStr();
                return lastMessageDateTime;

            };
            self.MoreStatus = function() {
                var url = "";
                if (self.ListMode() == listModeEnum.ListStatus) {
                    url = "/api/PostApi/HomeLine";
                } else {
                    url = "/api/PostApi/HomeLineProduct";
                }

                var lastMessageDateTime = self.LastCreatedAt();

                self.PageInfo = self.PageInfo.NextPage(lastMessageDateTime);
                $.ajax({
                    url:url,
                    type: 'post',
                    async: false,
                    data: ko.toJSON(self.PageInfo),
                    contentType: 'application/json',
                    success: function(result) {

                        if (result.Status == "0") {
                            var statusList = result.PostList;

                            $.each(statusList, function(index, a) {
                                var item = BuildListItemModel(a);
                                vm.Messages.push(item);


                            });

                        } else {
                            alert("保存失败：" + result.Msg);
                        }
                    }
                });
            };

            self.CreateFriendShip = function() {
                $.ajax({
                    url: "/api/FriendShipApi/Create",
                    type: 'post',
                    data: ko.toJSON(self),
                    contentType: 'application/json',
                    success: function(result) {

                        if (result.Status == "0") {
                            alert("保存成功");
                        } else {
                            alert("保存失败：" + result.Msg);
                        }
                    }
                });
            };

        }

        var vm = new HomeTimeLineModel();


        $(function() {          


            hub.client.success = function(a) {

                if (a.Status == "success") {
                    if (a.IsProductStatus) {
                        vm.ProductStatusModel.ProductDescription(''); //clear text
                        vm.ProductStatusModel.Pics([]); //clear pictures
                    } else {
                        vm.CustomerStatusModel.Text(''); //clear text
                        vm.CustomerStatusModel.Pics([]); //clear pictures

                        $('.tagedit-listelement-old').remove();

                    }

                    $('.qq-upload-success').remove(); //clear success upload picture notes
                }
            };
            hub.client.messageReceived = function(a) {
                var item = BuildListItemModel(a);
       
               
                vm.Messages.unshift(item );
            };

            $.connection.hub.start().done(function() {
            });

            ko.applyBindings(vm);

            $("#tagform-full").find('input.tag').tagedit({
                autocompleteURL: '/tags/GetTags',
                allowDelete: false,                
            });
        });

        function goDetail() {


        }

        $(document).ready(function() {

            var errorHandler = function(event, id, fileName, reason) {
                qq.log("id: " + id + ", fileName: " + fileName + ", reason: " + reason);
            };


            var uploader2 = new qq.FineUploader({
                element: $('#manualUploadModeExample1')[0],
                autoUpload: true,              
                
                text: {
                    uploadButton: '<div><i class="icon-upload icon-white"></i> +</div>'
                },
                template: '<div class="qq-uploader span12">' +
                    '<pre class="qq-upload-drop-area span12"><span>{dragZoneText}</span></pre>' +
                    '<div class="qq-upload-button btn " style="width: auto;">{uploadButtonText}</div>' +
                    '<span class="qq-drop-processing"><span>{dropProcessingText}</span><span class="qq-drop-processing-spinner"></span></span>' +
                    '<ul class="qq-upload-list" style="margin-top: 10px; text-align: center;"></ul>' +
                    '</div>',
                classes: {
                    success: 'alert alert-success',
                    fail: 'alert alert-error'
                },
                request: {
                    endpoint: "/FineUploader/UploadFile",
                    params: { "extraParam1": "true", "picSize": "80" }
                },
                callbacks: {
                    onError: errorHandler,
                    onComplete: function(id, fileName, responseJSON) {
                        if (responseJSON.success) {
                            //vm.PictureId(responseJSON.PictureId);
                            //vm.PictureUrl(responseJSON.PictureUrl);
                            vm.CustomerStatusModel.Pics.push(new PostPictureModel(responseJSON.OriginalPictureId, responseJSON.NewPictureUrl));

                        }
                    }
                }
            });


            //var uploader1 = new qq.FineUploader({
            //    element: $('#manualUploadModeExample2')[0],
            //    autoUpload: true,               

            //    text: {
            //        uploadButton: '<div><i class="icon-upload icon-white"></i> +</div>'
            //    },
            //    template: '<div class="qq-uploader span12">' +
            //        '<pre class="qq-upload-drop-area span12"><span>{dragZoneText}</span></pre>' +
            //        '<div class="qq-upload-button btn " style="width: auto;">{uploadButtonText}</div>' +
            //        '<span class="qq-drop-processing"><span>{dropProcessingText}</span><span class="qq-drop-processing-spinner"></span></span>' +
            //        '<ul class="qq-upload-list" style="margin-top: 10px; text-align: center;"></ul>' +
            //        '</div>',
            //    classes: {
            //        success: 'alert alert-success',
            //        fail: 'alert alert-error'
            //    },
            //    request: {
            //        endpoint: "/FineUploader/UploadFile",
            //        params: { "extraParam1": "true", "picSize": "80" }
            //    },
            //    callbacks: {
            //        onError: errorHandler,
            //        onComplete: function(id, fileName, responseJSON) {
            //            if (responseJSON.success) {
            //                //vm.PictureId(responseJSON.PictureId);
            //                //vm.PictureUrl(responseJSON.PictureUrl);
            //                vm.ProductStatusModel.Pics.push(new PostPictureModel(responseJSON.OriginalPictureId, responseJSON.NewPictureUrl));
            //            }
            //        }
            //    }
            //});
          

        });
    </script>

    <script src="~/Content/tagedit/js/jquery-ui-1.8.6.custom.min.js"></script>
    <script type="text/javascript" src="/Content/tagedit/js/jquery.autoGrowInput.js"></script>
    <script type="text/javascript" src="/Content/tagedit/js/jquery.tagedit.js"></script>
}


